package com.hbnu.jdbc;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
import java.util.ResourceBundle;

/**
 * @author kittychen
 * @since 2025-10-22 17:24
 */
public class JdbcDemo02 {
    public static void main(String[] args) {
        // 通过ResourceBundle读取配置文件
        // ResourceBundle resourceBundle = ResourceBundle.getBundle("jdbc");
        // String driver = resourceBundle.getString("driver");
        // String url = resourceBundle.getString("url");
        // String user = resourceBundle.getString("username");
        // String password = resourceBundle.getString("password");

        Connection connection = null;
        Statement statement = null;
        try {
            // 通过反射读取数据库配置文件
            InputStream resourceAsStream = JdbcDemo02.class.getClassLoader().getResourceAsStream("jdbc.properties");
            Properties properties = new Properties();
            properties.load(resourceAsStream);

            String driver = properties.getProperty("driver");
            String url = properties.getProperty("url");
            String user = properties.getProperty("username");
            String password = properties.getProperty("password");

            Class.forName(driver);

            connection = DriverManager.getConnection(url, user, password);

            statement = connection.createStatement();

            String sql = "insert into tb_user values(3,'kittychen','123456', 50000)";
            int row = statement.executeUpdate(sql);
            System.out.println(row > 0 ? "success" : "fail");
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if (statement != null) {
                    statement.close();
                }
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }

            try {
                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
